package com.xyb.service;

import com.xyb.dao.CourseDetailDao;
import com.xyb.entity.CourseDetail;
import com.xyb.utils.IdUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class CourseDetailService {
    @Resource
    private IdUtils idUtils;
    @Resource
    private CourseDetailDao courseDetailDao;

    public CourseDetail selectCourseDetailByCourseDetailId(Long courseDetailId) {
        Optional<CourseDetail> courseDetail = courseDetailDao.findById(courseDetailId);
        return courseDetail.get();
    }

    public String insertCourseDetailByChapterId(CourseDetail courseDetail) {
        long nextId = idUtils.nextId();
        courseDetail.setCourseDetailId(nextId);

        Integer showOrder = courseDetailDao.countByChapterId(courseDetail.getChapterId());
        courseDetail.setShowOrder(showOrder == null ? 0 : showOrder++);
        courseDetail.setStatus(1);
        courseDetail.setCreateTime(new Date());

        courseDetailDao.save(courseDetail);
        return "success";
    }

    public String deleteCourseDetailByCourseDetailId(Long courseDetailId) {
        courseDetailDao.deleteById(courseDetailId);
        return "success";
    }

    public String updateCourseDetailByCourseDetailId(CourseDetail courseDetail) {
        courseDetailDao.save(courseDetail);
        return "success";
    }

    public String updateCourseDetailShowOrder(Long[] courseDetailIds) {
        List<CourseDetail> list = new ArrayList<>();
        for (int i = 0, length = courseDetailIds.length; i < length; i++) {
            CourseDetail courseDetail = new CourseDetail();
            courseDetail.setCourseDetailId(courseDetailIds[i]);
            courseDetail.setShowOrder(i);
            list.add(courseDetail);
        }
        courseDetailDao.saveAll(list);
        return "success";
    }
}
